package com.witmore.skyline.web.service.impl;

import com.witmore.skyline.db.entity.CameraPicDO;
import com.witmore.skyline.web.service.PictureAnalysisService;
import com.witmore.skyline.web.service.PictureService;
import com.witmore.skyline.web.service.third.aliyun.QpsLimitedPedestrianDetectionService;
import com.witmore.skyline.web.service.third.aliyun.dto.PedestrianDetectionResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

/**
 * 图片分析服务实现类 - 封装人体检测和AI分析的通用逻辑
 * @author 豆子高
 * @date 2025-01-01
 */
@Slf4j
@Service
public class PictureAnalysisServiceImpl implements PictureAnalysisService {

    @Autowired
    private QpsLimitedPedestrianDetectionService qpsLimitedPedestrianDetectionService;

    @Lazy
    @Autowired
    private PictureService pictureService;

    @Override
    public CameraPicDO analyzeWithHumanDetection(String picUrl, String cameraSn, String logPrefix) throws Exception {
        // 1. 首先进行人体检测（带QPS限制）
        try {
            log.info("{}：开始人体检测，图片URL：{}", logPrefix, picUrl);
            PedestrianDetectionResult detectionResult = qpsLimitedPedestrianDetectionService.detectPedestrian(picUrl);

            if (!detectionResult.isHasHuman()) {
                // 没有检测到人体，返回特殊结果对象
                log.info("{}：未检测到人体，图片URL：{}，跳过AI分析", logPrefix, picUrl);
                return createNoHumanResult();
            }

            log.info("{}：检测到人体，继续进行AI分析，人体数量：{}", logPrefix, detectionResult.getHumanCount());

        } catch (Exception e) {
            log.error("{}：人体检测失败，图片URL：{}，错误信息：{}，继续进行AI分析", logPrefix, picUrl, e.getMessage());
            // 人体检测失败时，继续进行AI分析
        }

        // 2. 有人体或人体检测失败时，继续进行AI分析
        return pictureService.neutronChatCompletions(picUrl, cameraSn);
    }

    /**
     * 创建无人体检测结果
     */
    private CameraPicDO createNoHumanResult() {
        return CameraPicDO.builder()
                .aiLevelType(0)
                .aiLevel("无人体数据")
                .analyzeStatus(1)
                .aiMessage("画面中无人形数据，无需进行AI分析")
                .aiResult("画面中无人形数据")
                .build();
    }
}
